package org.xtense.rcp.editors.action;

import org.dom4j.Attribute;
import org.dom4j.Element;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Item;
import org.xtense.rcp.editors.XmlEditor;
import org.xtense.rcp.editors.util.XmlEntry;

public class XmlCellModifier implements ICellModifier {
	private TreeViewer tv;
	private XmlEditor editor;
	private boolean doubleClick;
	private Object element;
	private String property;

	public XmlCellModifier(final TreeViewer tv, XmlEditor editor) {
		super();
		this.tv = tv;
		this.editor = editor;
		tv.getTree().addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(MouseEvent e) {
				doubleClick = true;
				if (XmlEditor.Col_Name.equals(property)) {
					tv.editElement(element, 0);
				} else {
					tv.editElement(element, 1);
				}
				doubleClick = false;
			}
		});
	}

	@Override
	public boolean canModify(Object element, String property) {
		this.element = element;
		this.property = property;
		if (doubleClick) {
			if (element instanceof XmlEntry) {
				XmlEntry entry = (XmlEntry) element;
				if (entry.getType() == XmlEntry.Attribute) {
					return false;
				}
			}
			return true;
		} else {
			if (XmlEditor.Col_Value.equals(property)) {
				return true;
			} else {
				return false;
			}
		}
	}

	@Override
	public Object getValue(Object element, String property) {
		if (element instanceof XmlEntry) {
			XmlEntry entry = (XmlEntry) element;
			if (XmlEditor.Col_Name.equals(property)) {
				return entry.getName();
			} else if (XmlEditor.Col_Value.equals(property)) {
				return entry.getValue();
			}
		}
		return null;
	}

	@Override
	public void modify(Object element, String property, Object value) {
		if (element instanceof Item) {
			Object data = ((Item) element).getData();
			if (data instanceof XmlEntry) {
				XmlEntry entry = (XmlEntry) data;
				if (XmlEditor.Col_Name.equals(property)) {
					if (!entry.getName().equals(value)) {
						editor.setDirty(true);
						entry.setName((String) value);
						
						// update the model node
						if (entry.getType() == XmlEntry.Element) {
							entry.getNode().setName(value.toString());
						}
					}
				} else if (XmlEditor.Col_Value.equals(property)) {
					if (!entry.getValue().equals(value)) {
						editor.setDirty(true);
						entry.setValue((String) value);
						
						// update the model node
						if (entry.getType() == XmlEntry.Element) {
							((Element) entry.getNode()).setText(value
									.toString());
						} else {
							((Attribute) entry.getNode()).setValue(value
									.toString());
						}
					}
				}
				tv.update(entry, null);
			}
		}
	}

}
